<template>
	<div class="index-container">
		<el-carousel :interval="5000" height="500px" type="card" class="banner">
			<el-carousel-item v-for="(item, index) in featuredItems" :key="index">
				<div class="carousel-content" @click="navigateToDetail(item.id)">
					<img :src="'/api' + item.cover" :alt="item.name" class="carousel-image">
					<div class="carousel-caption">
						<h2>{{ item.name }}</h2>
						<p>{{ item.shortDescription }}</p>
					</div>
				</div>
			</el-carousel-item>
		</el-carousel>
		
		<div class="search-section">
			<el-row :gutter="20">
				<el-col :xs="24" :sm="18">
					<el-input 
						v-model="searchQuery" 
						placeholder="搜索甘肃传统手工艺品..." 
						prefix-icon="Search"
						@keyup.enter="handleSearch"
						clearable
					/>
				</el-col>
				<el-col :xs="24" :sm="6">
					<el-button type="primary" @click="handleSearch" style="width: 100%">搜索</el-button>
				</el-col>
			</el-row>

		</div>
		
		<div class="recommendation-section">
			<h2 class="section-title">
				<span class="title-text">为您推荐</span>
				<el-tooltip content="根据您的浏览历史和兴趣推荐" placement="top">
					<el-icon class="info-icon"><InfoFilled /></el-icon>
				</el-tooltip>
			</h2>
			
			<el-empty v-if="isLoading" :description="false">
				<el-skeleton :rows="3" animated />
			</el-empty>
			
			<el-empty v-else-if="personalRecommendations.length === 0" description="暂无推荐，浏览更多内容获取个性化推荐" />
			
			<div v-else class="recommendation-grid">
				<div 
					v-for="item in personalRecommendations" 
					:key="item.id" 
					class="goods-card"
					@click="navigateToDetail(item.id)"
				>
					<goods-item :item="item" />
					<div class="recommendation-reason" v-if="item.reasons && item.reasons.length">
						<el-tooltip 
							v-for="(reason, idx) in item.reasons" 
							:key="idx"
							:content="typeof reason === 'string' ? reason : (reason.type + ': ' + reason.name)"
							placement="top"
						>
							<el-tag size="small" effect="plain" class="reason-tag">
								{{ typeof reason === 'string' ? reason : reason.name }}
							</el-tag>
						</el-tooltip>
					</div>
				</div>
			</div>
		</div>
		
		<div class="categories-section">
			<h2 class="section-title">
				<span class="title-text">工艺分类</span>
			</h2>
			
			<el-row :gutter="20">
				<el-col 
					v-for="category in categories" 
					:key="category.id" 
					:xs="12" :sm="8" :md="6" :lg="4"
				>
					<div class="category-card" @click="navigateToCategory(category.id)">
						<el-image :src="'/api' + category.cover" fit="cover" class="category-image" />
						<div class="category-name">{{ category.name }}</div>
					</div>
				</el-col>
			</el-row>
		</div>
		
		<div class="cultural-section">
			<h2 class="section-title">
				<span class="title-text">历史文化发现</span>
			</h2>
			
			<el-empty v-if="isLoading" :description="false">
				<el-skeleton :rows="3" animated />
			</el-empty>
			
			<el-empty v-else-if="culturalRecommendations.length === 0" description="暂无历史文化推荐" />
			
			<div v-else class="cultural-grid">
				<div 
					v-for="item in culturalRecommendations" 
					:key="item.id" 
					class="cultural-card"
					@click="navigateToDetail(item.id)"
				>
					<el-card shadow="hover" class="cultural-item">
						<div class="cultural-image-container">
							<el-image :src="'/api' + item.cover" fit="cover" class="cultural-image" />
						</div>
						<div class="cultural-content">
							<h3>{{ item.name }}</h3>
							<p class="cultural-description">{{ getShortDescription(item) }}</p>
							<div class="cultural-tags">
								<el-tag 
									v-for="(tag, idx) in item.tags" 
									:key="idx" 
									type="info" 
									effect="plain"
									class="cultural-tag"
								>
									{{ tag.name }}
								</el-tag>
								<el-tag type="primary" v-if="item.category">{{ item.category.name }}</el-tag>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { Search, InfoFilled } from '@element-plus/icons-vue';
import GoodsItem from '@/components/goodsItem/Index.vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { typesApi } from '@/api/type.js';
import { goodsListApi } from '@/api/goods.js';
import {historicalApi, personalizedApi} from '@/api/recommend.js'

const router = useRouter();
const searchQuery = ref('');
const isLoading = ref(true);
const personalRecommendations = ref([]);
const culturalRecommendations = ref([]);
const featuredItems = ref([]);
const categories = ref([]);
const selectedCategories = ref([]);

// 获取个性化推荐数据
const fetchPersonalRecommendations = async () => {
	try {
		const res = await personalizedApi();
		if (res.code === 200) {
			personalRecommendations.value = res.data || [];
		} else {
			console.error('获取个性化推荐返回错误:', res.message);
			personalRecommendations.value = [];
		}
	} catch (error) {
		console.error('获取个性化推荐失败:', error);
		personalRecommendations.value = [];
	}
};

// 获取文化历史推荐数据
const fetchCulturalRecommendations = async () => {
	try {
		const res = await historicalApi();
		if (res.code === 200) {
			culturalRecommendations.value = res.data || [];
		} else {
			console.error('获取文化历史推荐返回错误:', res.message);
			culturalRecommendations.value = [];
		}
	} catch (error) {
		console.error('获取文化历史推荐失败:', error);
		culturalRecommendations.value = [];
	}
};

// 获取推荐展示商品
const fetchFeaturedItems = async () => {
	try {
		const response = await goodsListApi({ page: 1, pageSize: 5 });
		if (response.code === 200) {
			featuredItems.value = response.list.map(item => ({
				...item,
				shortDescription: getShortDescription(item)
			}));
		}
	} catch (error) {
		console.error('获取推荐展示商品失败:', error);
	}
};

// 获取所有分类
const fetchCategories = async () => {
	try {
		const response = await typesApi();
		if (response.code === 200) {
			categories.value = response.data;
		}
	} catch (error) {
		console.error('获取分类失败:', error);
	}
};

// 获取商品简短描述
const getShortDescription = (item) => {
	if (item.history?.cultural_background) {
		return item.history.cultural_background.substring(0, 80) + '...';
	} else if (item.content) {
		// 移除HTML标签
		const textContent = item.content.replace(/<[^>]+>/g, '');
		return textContent.substring(0, 80) + '...';
	}
	return '暂无描述';
};

// 切换分类选择
const toggleCategory = (categoryId) => {
	const index = selectedCategories.value.indexOf(categoryId);
	if (index === -1) {
		selectedCategories.value.push(categoryId);
	} else {
		selectedCategories.value.splice(index, 1);
	}
};

// 跳转到详情页
const navigateToDetail = (id) => {
	router.push(`/detail/${id}`);
};

// 跳转到分类页
const navigateToCategory = (categoryId) => {
	router.push({
		path: '/search',
		query: { category: categoryId }
	});
};

// 处理搜索
const handleSearch = () => {
	const query = {};
	if (searchQuery.value.trim()) {
		query.keyword = searchQuery.value.trim();
	}
	if (selectedCategories.value.length > 0) {
		query.categories = selectedCategories.value.join(',');
	}
	
	router.push({
		path: '/search',
		query
	});
};

// 添加统一的数据加载函数
const loadAllData = async () => {
	isLoading.value = true;
	try {
		await Promise.all([
			fetchPersonalRecommendations(),
			fetchCulturalRecommendations(),
			fetchFeaturedItems(),
			fetchCategories()
		]);
	} catch (error) {
		console.error('加载数据失败:', error);
		ElMessage.error('加载数据失败，请稍后重试');
	} finally {
		isLoading.value = false;
	}
};

// 在生命周期钩子部分修改
onMounted(async () => {
	loadAllData();
});

// 添加 onActivated 生命周期钩子，确保从其他页面返回时重新加载数据
onActivated(async () => {
	// 检查是否已加载数据，如果没有则加载
	if (
		personalRecommendations.value.length === 0 || 
		culturalRecommendations.value.length === 0 || 
		featuredItems.value.length === 0 ||
		categories.value.length === 0
	) {
		console.log('重新加载首页数据');
		loadAllData();
	}
});
</script>

<style scoped lang="scss">
.index-container {
	max-width: 1200px;
	margin: 0 auto;
	padding: 20px;
}

.banner {
	margin-bottom: 40px;
}

.carousel-content {
	height: 100%;
	position: relative;
	cursor: pointer;
	border-radius: 8px;
	overflow: hidden;
}

.carousel-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.carousel-caption {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(0, 0, 0, 0.6);
	color: white;
	padding: 20px;
	
	h2 {
		margin: 0 0 10px;
		font-size: 24px;
	}
	
	p {
		margin: 0;
		font-size: 14px;
	}
}

.search-section {
	margin-bottom: 40px;
	padding: 20px;
	background-color: #f8f9fa;
	border-radius: 8px;
	
	.filter-tags {
		margin-top: 15px;
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		
		.filter-tag {
			cursor: pointer;
			&:hover {
				opacity: 0.8;
			}
		}
	}
}

.section-title {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
	padding-bottom: 10px;
	border-bottom: 1px solid #eee;
	
	.title-text {
		font-size: 22px;
		font-weight: bold;
	}
	
	.info-icon {
		margin-left: 8px;
		color: #909399;
	}
}

.recommendation-section,
.categories-section,
.cultural-section {
	margin-bottom: 40px;
}

.recommendation-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
	gap: 20px;
}

.goods-card {
	cursor: pointer;
	transition: transform 0.3s;
	
	&:hover {
		transform: translateY(-5px);
	}
	
	.recommendation-reason {
		margin-top: 10px;
		display: flex;
		flex-wrap: wrap;
		gap: 5px;
		
		.reason-tag {
			max-width: 100%;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}

.category-card {
	cursor: pointer;
	border-radius: 8px;
	overflow: hidden;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	margin-bottom: 20px;
	transition: transform 0.3s;
	
	&:hover {
		transform: translateY(-5px);
	}
	
	.category-image {
		width: 100%;
		height: 120px;
	}
	
	.category-name {
		padding: 10px;
		text-align: center;
		font-weight: bold;
	}
}

.cultural-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
	gap: 20px;
}

.cultural-card {
	cursor: pointer;
	
	.cultural-item {
		transition: transform 0.3s;
		
		&:hover {
			transform: translateY(-5px);
		}
	}
	
	.cultural-image-container {
		height: 180px;
		overflow: hidden;
		
		.cultural-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}
	}
	
	.cultural-content {
		padding: 10px 0;
		
		h3 {
			margin: 0 0 10px;
			font-size: 18px;
		}
		
		.cultural-description {
			margin-bottom: 10px;
			color: #606266;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
		}
		
		.cultural-tags {
			display: flex;
			flex-wrap: wrap;
			gap: 5px;
			
			.cultural-tag {
				max-width: 100%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}
}

@media (max-width: 768px) {
	.cultural-grid {
		grid-template-columns: 1fr;
	}
	
	.carousel-caption {
		h2 {
			font-size: 18px;
		}
		
		p {
			font-size: 12px;
		}
	}
}
</style>
